const KEYS = ['hisCities', 'planCity', 'chatCity']

const getDefaultState = () => {
  const result = {}
  result.hisCities = uni.getStorageSync('hisCities') || []
  result.planCity = uni.getStorageSync('planCity') || ''
  result.chatCity = uni.getStorageSync('chatCity') || ''
  return result
}

const state = getDefaultState()

const mutations = {
  SET_CITY: (state, cityInfo) => {
    if (cityInfo) {
      let origin = cityInfo.origin
      let city = cityInfo.city
      let cityKey = origin + "City"
      state[cityKey] = city
      uni.setStorageSync(cityKey, city)
      
      let hisCities = state.hisCities
      if (hisCities.indexOf(city) < 0) {
        hisCities.push(city)
      }
      state['hisCities'] = hisCities
      uni.setStorageSync("hisCities", hisCities)
    } else {
      state['hisCities'] = []
      uni.setStorageSync("chatCity", "")
      uni.setStorageSync("planCity", "")
      uni.setStorageSync("hisCities", [])
    }
  }
}

const actions = {
  addCity({ state, commit }, city) {
    if (city) {
      commit('SET_CITY', city);
    }
    return new Promise(resolve => {
      resolve(city)
    })
  },
  getCity({ state }, origin) {
    let cityJson = state.curCity
    let result = ''
    if (cityJson) {
      result = JSON.parse(cityJson)[origin]
    }
    return result
  },
  clear({ state, commit }) {
    commit('SET_CITY', '');
    return Promise.resolve()
  },
  getHistroy({ state }) {
    return new Promise(resolve => {
      resolve(state.hisCities)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
